package com.ymt.bpm.web.rest.engine.process;

import com.alibaba.fastjson.JSONObject;
import com.ymt.bpm.engine.listener.engine.exception.EngineException;
import com.ymt.bpm.engine.listener.engine.exception.ErrorCode;
import com.ymt.bpm.model.PPiHi;
import com.ymt.bpm.service.engine.task.PiService;
import com.ymt.bpm.service.platform.log.SysLogService;
import com.ymt.bpm.util.AES;
import com.ymt.bpm.util.Const;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Created by Johnny on 2017/4/17.
 */
@RestController
@RequestMapping("/api/v1/engine/process/pi")
public class PiResource {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private PiService pis;

    @Autowired
    private SysLogService sls;

    @GetMapping("/{piEid}")
    public JSONObject get(HttpServletRequest req,
                          @PathVariable("piEid")String piEidEn,
                          @RequestParam("timezoneOffset")int timezoneOffset) {
        Map<String, String> userDetail = (Map<String, String>) SecurityContextHolder.getContext().getAuthentication().getDetails();
        String tenantId = userDetail.get(Const.TENANT_ID);
        String lang = userDetail.get(Const.LANG);
        String piEid = AES.decrypt(piEidEn);
        if (log.isDebugEnabled()) {
            log.debug("get tenantId="+tenantId);
            log.debug("get lang="+lang);
            log.debug("get timezoneOffset="+timezoneOffset);
        }
        return pis.get(tenantId, piEid, lang, timezoneOffset);
    }

    /*@PostMapping("/startProcess")
    public JSONObject startProcess(HttpServletRequest req, @RequestBody JSONObject args) {
        String tenantId = userDetail.get(Const.TENANT_ID);
        String loginName = userDetail.get(Const.LOGINNAME);
        String displayName = userDetail.get(Const.DISPLAYNAME);
        if (log.isDebugEnabled()) {
            log.debug("statePi tenantId="+tenantId);
            log.debug("statePi loginName="+loginName);
            log.debug("statePi displayName="+displayName);
            log.debug("statePi args="+args);
        }
        return pis.startProcess(tenantId, args.getString("bpdId"),
                args.getString("versionid"),
                args.getString("parentPiid"),
                loginName,
                displayName,
                args.getString("title"),
                args.getJSONObject("variables"));
    }*/

    @GetMapping("/state")
    public JSONObject statePi(HttpServletRequest req,
                              @RequestParam("action")String action,
                              @RequestParam("piId")String piId,
                              @RequestParam("status")String status) {
        Map<String, String> userDetail = (Map<String, String>) SecurityContextHolder.getContext().getAuthentication().getDetails();
        String tenantId = userDetail.get(Const.TENANT_ID);
        String loginName = userDetail.get(Const.LOGINNAME);
        String displayName = userDetail.get(Const.DISPLAYNAME);
        if (log.isDebugEnabled()) {
            log.debug("statePi tenantId="+tenantId);
            log.debug("statePi loginName="+loginName);
            log.debug("statePi displayName="+displayName);
            log.debug("statePi action="+action);
            log.debug("statePi piId="+piId);
            log.debug("statePi status="+status);
        }
        if ("statePi".equalsIgnoreCase(action)) {
            return pis.statePi(tenantId, loginName, displayName, piId, status);
        } else if ("statePiToHi".equalsIgnoreCase(action)) {
            String deleteReason = null;
            if (PPiHi.STATUS_TERMINATED.equals(status)) {
                deleteReason = "TERMINATE";
            }
            return pis.statePiToHi(tenantId, loginName, displayName, piId, status, deleteReason);
        } else if ("stateHi".equalsIgnoreCase(action)) {
            return pis.stateHi(tenantId, loginName, displayName, piId, status);
        } else {
            return null;
        }
    }

    @GetMapping("/getByCallActivityId")
    public JSONObject getByCallActivityId(HttpServletRequest req,
                              @RequestParam("piId")String piId,
                              @RequestParam("parentPiEid")String parentPiEid,
                              @RequestParam("callActivityId")String callActivityId,
                              @RequestParam("timezoneOffset")int timezoneOffset) {
        Map<String, String> userDetail = (Map<String, String>) SecurityContextHolder.getContext().getAuthentication().getDetails();
        String tenantId = userDetail.get(Const.TENANT_ID);
        String lang = userDetail.get(Const.LANG);
        if (log.isDebugEnabled()) {
            log.debug("getByCallActivityId tenantId="+tenantId);
            log.debug("getByCallActivityId piId="+piId);
            log.debug("getByCallActivityId parentPiEid="+parentPiEid);
            log.debug("getByCallActivityId callActivityId="+callActivityId);
            log.debug("getByCallActivityId lang="+lang);
            log.debug("getByCallActivityId timezoneOffset="+timezoneOffset);
        }
        return pis.getByCallActivityId(tenantId, piId, parentPiEid, callActivityId, lang, timezoneOffset);
    }

    @GetMapping("/infoForChange/{piEid}")
    public JSONObject infoForChange(HttpServletRequest req,
                              @PathVariable("piEid")String piEidEn,
                              @RequestParam("timezoneOffset")int timezoneOffset) {
        Map<String, String> userDetail = (Map<String, String>) SecurityContextHolder.getContext().getAuthentication().getDetails();
        String tenantId = userDetail.get(Const.TENANT_ID);
        String lang = userDetail.get(Const.LANG);
        String piEid = AES.decrypt(piEidEn);
        if (log.isDebugEnabled()) {
            log.debug("infoForChange tenantId="+tenantId);
            log.debug("infoForChange piEid="+piEid);
            log.debug("infoForChange lang="+lang);
            log.debug("infoForChange timezoneOffset="+timezoneOffset);
        }
        return pis.infoForChange(tenantId, piEid, lang, timezoneOffset);
    }

    @PostMapping("/saveDynamicChange/{piEid}")
    public JSONObject saveDynamicChange(HttpServletRequest req,
                                    @PathVariable("piEid")String piEidEn,
                                    @RequestParam("param") String param) {
        Map<String, String> userDetail = (Map<String, String>) SecurityContextHolder.getContext().getAuthentication().getDetails();
        String tenantId = userDetail.get(Const.TENANT_ID);
        String loginName = userDetail.get(Const.LOGINNAME);
        String displayName = userDetail.get(Const.DISPLAYNAME);
        String piEid = AES.decrypt(piEidEn);
        if (log.isDebugEnabled()) {
            log.debug("saveDynamicChange tenantId="+tenantId);
            log.debug("saveDynamicChange loginName="+loginName);
            log.debug("saveDynamicChange displayName="+displayName);
            log.debug("saveDynamicChange piEid="+piEid);
            log.debug("saveDynamicChange param="+param);
        }
        try {
            return pis.saveDynamicChange(tenantId, loginName, displayName, piEid, param);
        } catch (Exception e) {
            e.printStackTrace();
            try {
                sls.expLog(tenantId,
                        piEid,
                        "",
                        "",
                        "0",
                        loginName, displayName, new EngineException(ErrorCode.PI_FAIL, "Dynamic change failed.", e));
            }catch (Exception e1) {
            }
            return null;
        }
    }

}
